# cython: language_level=3
#!/usr/bin/python
# -- coding:utf8 --
import json

import requests

from . import util_log as utils_log, utils_sql
import pymysql
import pandas as pd

import warnings

warnings.filterwarnings("ignore")


def select_sql_mysql(sql):
    """
    风控库获取数据
    :param sql:
    :return:
    """
    conn = pymysql.Connect(
        host="159.138.99.18",
        port=3306,
        user="root",
        passwd="Qiuliu123!@#",
        database="adms_core_ph",
    )
    df = pd.read_sql(sql, con=conn)
    conn.close()
    return df


def select_sql_mysql_v1(sql):
    """
    从业务库里面获取数据集
    :param sql:
    :return:
    """
    conn = pymysql.Connect(
        host="119.13.100.83",
        port=3306,
        user="readonly",
        passwd="Gyt@20231122",
        database="phdcdb",
    )
    df = pd.read_sql(sql, con=conn)
    conn.close()
    return df


def get_is_none(x):
    """
    #判断参数是否为空
    Parameters
    ----------
    x：参数

    Returns
    -------
    返回布尔值
    """
    if x is None or str(x).replace(" ", "").lower().strip() in [
        "-999999",
        "-999976",
        "-999977",
        "-999978",
        "-999999.0",
        "-999976.0",
        "-999977.0",
        "-999978.0",
        "none",
        "nan",
        "nat",
        "",
        "000000000000000",
    ]:
        return True
    else:
        return False


def get_is_match(parameter1, parameter2):
    """
    判断是否完全匹配
    Parameters
    ----------
    parameter1：参数1
    parameter2：参数2

    Returns
    -------
    返回布尔值（1或者0）
    """
    try:
        if parameter1 == parameter2:
            return 1
        else:
            return 0
    except Exception as e:
        utils_log.get_logger().error(e)
        return -9976


def process_phone_number(phone_number):
    """
    手机号码处理，用于识别存储的数据表
    :param phone_number:
    :return:
    """
    # 清除空格
    phone_number = phone_number.replace(" ", "")

    # 第一步，截取后两位
    last_two_digits = phone_number[-2:]

    # 第二步，若第二位为0，取第一位
    if last_two_digits[0] == '0':
        processed_number = last_two_digits[1]
    else:
        processed_number = last_two_digits

    # 第三步，将字符转换为整数
    processed_number = int(processed_number)

    return processed_number


def load_remote_json(url):
    """
    发起HTTP请求获取远程JSON数据
    param url: 请求的URL
    """
    try:
        # 发起HTTP请求获取远程JSON数据
        response = requests.get(url)
        response.encoding = 'utf-8'  # 确保响应数据的编码为utf-8，以正确处理中文字符
        # print(response.text)
        return response.text
    except Exception as e:
        utils_log.get_logger().error(e)
        return None


def is_json_string(text):
    """
    判断字符串是否为JSON格式。
    param text:字符串
    """
    if isinstance(text, str):
        try:
            json.loads(text)
            return True
        except json.JSONDecodeError:
            return False
    return False


def parse_json(text):
    """
    解析字符串为JSON对象。
    param text:字符串
    """
    try:
        while isinstance(text, str) & is_json_string(text):
            text = json.loads(text)
        return text
    except Exception as e:
        utils_log.get_logger().error(e)
        return None


def cal_rate(cnt: float, total: float, decimals=2, default=-9999.0) -> float:
    """
    计算百分比
    :param cnt: 个数
    :param total: 总数
    :param decimals: 小数点位数
    :param default: 默认值-9999
    :return:
    """
    if total == 0:
        return round(default, decimals)
    return round(cnt / total, decimals)


def cal_compared(apply_no, features):
    # 查询数据库里的风控参数
    dimension_df = utils_sql.get_mysql_dimension(apply_no=apply_no)
    dimension_dict = dimension_df.to_dict() if dimension_df is not None else {}
    compared = {}

    for key in features:
        if key in dimension_dict.keys():
            compared[key] = ((str(dimension_dict[key]) + '==' + str(features[key]) + '=')
                             + str(dimension_dict[key] == features[key]))

    # 返回比较结果
    return compared
